<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 具体页面结构 -->

      <PageTools>
        <template #left>总记录数:20条</template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button icon="plus" type="primary" size="small" 
          @click="hAdd">
          新增员工
      </el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index"/>
          <el-table-column label="姓名" prop="username"/>
          <el-table-column label="头像">
          <template v-slot="scope">
            <!-- 封装图片组件方便复用(注册为全局组件) -->
            <ImageHolder :src="scope.row.staffPhoto" />
            <!--  <img :src="scope.row.staffPhoto"> -->
          </template>
          </el-table-column>
          <el-table-column label="工号"  prop="workNumber" sortable/>
          <el-table-column label="聘用形式">
            <!-- 插槽 -->
            <template slot-scope="scope">
              {{ formartType(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName"/>
          <el-table-column label="入职时间"  prop="timeOfEntry" sortable/>
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small"
              @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small"  @click="hAssignRole">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination 
          layout="total, sizes,prev, pager, next, jumper" 
          :total="total"
          :page-sizes="[2,5,10]"
          :current-page.sync="page"
          @size-change="hSizeChange"
          @current-change="hCurrentChange"/>
        </el-row>
      </el-card>
    </div>
    <!-- 弹框插槽 -->
    <el-dialog title="新增员工" :visible.sync="showDialog" :close-on-click-modal="false" @update-empolyee="hUpdateEmpolyee">
      <empDialog @success="hSuccess" />
    </el-dialog>

    <el-dialog
      title="分配角色"
      :visible.sync="showDialogRole"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <AssignRole />
    </el-dialog>
  </div>
</template>

<script>
// -----------------------------------导入员工数据列表请求、删除
import { getEmployees,delEmployee } from '@/api/employees'
// -----------------------------------导入枚举数据
import EmployeeEnum from '@/constant/employees'
// console.log('引用聘用形式枚举',EmployeeEnum.hireType)
// ------------------------------------导入子组件
import empDialog from './empDialog.vue'
import AssignRole from './AssignRole.vue'
export default {
  // 定义全局组件
  components: { empDialog, AssignRole },
  // ---------------------------------数据
  data(){
    return {
      size:10, // 每页几条数据
      page:1, // 当前显示第几页
      total:0, // 一共几条数据
      list:[],
      showDialogRole: false, // 分配角色的弹框
      showDialog: false, // 弹框显示隐藏
    }
  },
  // ------------------------------------页面一加载就执行渲染
  created(){
    // ----------------------------------页面渲染员工列表
    this.loadEmployees()
  },
  methods:{
     // 用户点击了分配角色
    hAssignRole() {
      this.showDialogRole = true
    },
    // ----------------------------------获取员工列表
    async loadEmployees(){
      const res = await getEmployees({page:this.page,size:this.size})
      // console.log('获取员工列表信息',res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // ----------------------------------获取聘用形式
    formartType(typeId){
      // 传入typeId寻找文件EmployeeEnum.hireType中的id
      const item = EmployeeEnum.hireType.find(item => item.id === typeId)
      if(item){
        return item.value
      }else{
        return '未知'
      }
    },
    // ----------------------------------页码
    hCurrentChange(curPage){
      // 更新页码
      this.page = curPage
      // 发送请求
      this.loadEmployees()
    },
    // ----------------------------------改变页码
    hSizeChange(curSize){
      console.log(curSize)
      // 更新每页几条
      this.page = 1
      this.size = curSize
      // 发送请求
      this.loadEmployees()
    },
     // ---------------------------------点击显示删除弹框
    hDel(id){
      this.$confirm('是否要删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {

      })
    },
    // ----------------------------------封装删除函数，点击确认删除时执行
    async doDel(id){
      await delEmployee(id)
      // 如果删除是最后一条数据，则页码要-1，页码不能是0
      if (this.list.length === 1){
          let page = this.page
          page--
          // 更新数据
          page = Math.max( 1, page )
          this.page = page
      }
      this.loadEmployees()
      // 显示提示信息
      this.$message.success('删除成功')
    },
    hAdd(){
      this.showDialog = true
    },
    // ----------------------------------收到子组件抛出的添加成功的事件
    hUpdateEmpolyee() {
      this.showDialog = false
      this.loadEmployeeList()
    },
    hSuccess(){
      this.showDialog=false
      this.total++
      this.page = Math.ceil(this.total/this.size)
      this.loadEmployees()
    },
    // ----------------------------------导出数据为excel文件
    hExportExcel(){
      import('@/vendor/Export2Excel').then(async excel => {
        // 1. 发请求
        const res = await getEmployees({ page: this.page, size: this.size })
        console.log('要导出的数据', res.data.rows)
        
        // 2. 格式转换，得到header, data(解构)
        const { header, data } = this.transformData(res.data.rows)
        // const rows = [
        //   {
        //     'id': '604f764971f93f3ac8f365c2',
        //     'mobile': '13800000002',)
        console.log(header, data)
        // 3.导出
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成文件类型
        })
      })
    },
    transformData(rows) {
      // rows:  [
      //   {id:'01', mobile:'13612345678'},
      //   {id:'02', mobile:'13612345679'}
      // ]
      const header = Object.keys(rows[0]) // ['id', 'mobile']
      const data = rows.map(item => {
        return header.map(key => {
          return item[key]
        })
        // return Object.values(item)
      })
      // todo: (1)表头要是中文的 (2) 聘用形式 不要是1，而是'正式'

      // [
      //   ['01', '13612345678'],
      //   ['02', '13612345679']
      // ]
      return {
        header, data
      }
    },
  }
}
</script>